import { defineStore } from 'pinia'
import { useOauth } from '@/composables/useOauth'

export const useAppStore = defineStore('app', () => {
  const showLogin = ref(false)
  const isLogin = ref(uni.getStorageSync('isLogin') || false)
  const isWorker = ref(uni.getStorageSync('isWorker') || false)
  const userInfo = reactive(uni.getStorageSync('userInfo') || {
    isRegister: 0,
  })
  const setIsLogin = (bool: boolean) => {
    isLogin.value = bool
    uni.setStorageSync('isLogin', bool)
  }
  const updateUser = (info: Record<string, any>) => {
    uni.setStorageSync('userInfo', Object.assign(userInfo, info))
  }
  const onShowLogin = (bool: boolean) => {
    showLogin.value = bool
  }
  const setIsWorker = (bool: boolean) => {
    isWorker.value = bool
    uni.setStorageSync('isWorker', bool)
  }


  const getUser = () => {
    return uni.getStorageSync('userInfo') || {
      isRegister: 0,
    }
  }

  const getIsRegister = () => {
    const info = getUser()
    return Number(info.isRegister || 0) === 1
  }

  const getIsLogin = () => {
    return uni.getStorageSync('isLogin') || false
  }

  const getIsWorker = () => {
    return uni.getStorageSync('isWorker') || false
  }


  const login = async (app: any) => {
    const loginRes: any = await useOauth()
    const res: any = await app.post('/api/login', {
      code: loginRes.code,
    })
    if (res.type === 'success') {
      setIsLogin(true)
      uni.setStorageSync('token', res.token)
      uni.setStorageSync('session_key', res.session_key)
      uni.setStorageSync('userInfo', res.userInfo)
      return res.userInfo
    }
    else {
      return {}
    }
  }

  return {
    showLogin,
    isLogin,
    isWorker,
    userInfo,
    setIsLogin,
    onShowLogin,
    updateUser,
    setIsWorker,
    getIsRegister,
    login,
    getIsLogin,
    getIsWorker,
    getUser
  }
})
